package com.atguigu.gulimall.ware.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyRabbitConfig extends Object{
    /**
     * 使用序列话机制进行消息转换
     */
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 创建交换机
     */
    @Bean
    public Exchange stockEventExChange(){
        return new TopicExchange("stock-event-exchange",true,false);
    }

    /**
     * 创建接受延迟队列
     */
    @Bean
    public Queue stockReleaseStockQueue(){
        //String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
        return new Queue("stock-release-stock",true,false,false);
    }

    /**
     * 延迟队列
     * @return
     */
    @Bean
    public Queue stockDelayQueue(){
        //String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
        Map<String,Object> map = new HashMap<>();
        map.put("x-dead-letter-exchange","stock-event-exchange");
        map.put("x-dead-letter-routing-key","stock.release");//路由给普通队列
        map.put("x-message-ttl",120000);//2分钟
        return new Queue("stock-delay-stock",true,false,false,map);

//        return QueueBuilder.durable("stock-delay-stock")
//                .withArgument("x-dead-letter-exchange","stock-event-exchange")  //当队列过期 则会进入到死信队列中
//                .withArgument("x-dead-letter-routing-key","stock.release")   //把死信队列路由到其他队列中
//                .build();
    }
    /**
     * 延迟队列邦定交换机
     */
    @Bean
    public Binding stockLockedBinding(){
        return new Binding("stock-delay-stock",
                                 Binding.DestinationType.QUEUE,
                                 "stock-event-exchange",
                                 "stock.locked",null);
    }

    /**
     * 普通队列邦定交换机
     */
    @Bean
    public Binding stockReleaseBinding(){
        return new Binding("stock-release-stock",
                                 Binding.DestinationType.QUEUE,
                                 "stock-event-exchange",
                                 "stock.release",null);
    }
}
